package com.androidproject.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONArray;
import org.json.JSONObject;

import com.androidproject.Constantes;
import com.androidproject.Header;
import com.androidproject.Item;
import com.androidproject.R;
import com.androidproject.LineArrayAdapter;
import com.androidproject.modele.Calendrier;
import com.androidproject.modele.CalendrierG;
import com.androidproject.modele.CalendrierParJour;

import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class CalendrierActivity extends ListActivity {

	private Intent intentAccueil;
	private Intent intentClassement;
	private Intent intentCalendrier;
	private Intent intentProgrammeTV;
	private Intent intentFacebook;
	private Intent intentTwitter;
	private List<Item> items;
	private CalendrierG calendrierg;
	private ProgressDialog progressD;
	
	public class TaskObject extends AsyncTask<String, Void, StringBuffer> {

		private HttpResponse response;
		private JSONObject jSonObject;
		
		@Override
		//String... pour sp�cifier qu'il n'y a pas de nombre de param�tre sp�cifique,
		///il faut juste que ce soit le m�me type
		protected StringBuffer doInBackground(String... url) {
			
			StringBuffer chaine = new StringBuffer("");
			
			try{
				
				AndroidHttpClient client = AndroidHttpClient.newInstance("user-agent"); 
				URI uri = new URI(url[0]);
				HttpGet request = new HttpGet(); 
				request.setURI(uri); 
				response = client.execute(request); 
				client.close();
				
				// Get the response 
				InputStream inputStream = response.getEntity().getContent(); 
				BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); 
				String line = "";
				
				while ((line = rd.readLine()) != null) { 
					chaine.append(line);
				} 
				
			} catch(Exception e){ 
				chaine.append(e.getMessage());
				
			} finally { } 
			
			return chaine;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressD = ProgressDialog.show(CalendrierActivity.this, Constantes.WAIT_TITLE,Constantes.WAIT_MESSAGE_CALENDRIER, true);
		}
		
		@Override
		protected void onPostExecute(StringBuffer result) {
			
			super.onPostExecute(result);
			
			progressD.dismiss();
			
			try{ //Traitement du JSON 
				
				String newString = result.toString();
				
				jSonObject = new JSONObject(newString);
				JSONObject resultatCal = jSonObject.getJSONObject(Constantes.CALENDRIER_CALENDAR);
				
				//Création du calendrier
				calendrierg = new CalendrierG();
				
				//Récupération des enfants
				for(int index = 0; index < resultatCal.length(); index++){
					JSONArray d0 = new JSONArray(resultatCal.getString("D"+index));
					CalendrierParJour calendrierPJ = new CalendrierParJour(d0.getJSONObject(0).getString(Constantes.CALENDRIER_LABEL));
					
					for(int i = 0; i< d0.length(); i++){ 
						Calendrier calendrier = new Calendrier(d0.getJSONObject(i).getString(Constantes.CALENDRIER_LABEL),
															d0.getJSONObject(i).getString(Constantes.CALENDRIER_TEAM1),
															d0.getJSONObject(i).getString(Constantes.CALENDRIER_TEAM2),
															d0.getJSONObject(i).getString(Constantes.CALENDRIER_SCORE1),
															d0.getJSONObject(i).getString(Constantes.CALENDRIER_SCORE2),
															d0.getJSONObject(i).getString(Constantes.CALENDRIER_DAY),
															d0.getJSONObject(i).getString(Constantes.CALENDRIER_MONTH),
															d0.getJSONObject(i).getString(Constantes.CALENDRIER_YEAR),
															d0.getJSONObject(i).getString(Constantes.CALENDRIER_HOUR),
															d0.getJSONObject(i).getString(Constantes.CALENDRIER_MIN),
															d0.getJSONObject(i).getString(Constantes.CALENDRIER_FINAL));
						calendrierPJ.getCalendriers().add(calendrier);
					}
					calendrierg.getListJours().add(calendrierPJ);
				}
				
				items = new ArrayList<Item>();
				
				for (CalendrierParJour calendrierPJ : calendrierg.getListJours()) {
					
					 items.add(new Header(calendrierPJ.getLabel()));
						
					for (Calendrier calendrier : calendrierPJ.getCalendriers()) {
						items.add(new Calendrier("", calendrier.getTeam1(), calendrier.getTeam2(), calendrier.getScore1(), calendrier.getScore2(), calendrier.getDay(), calendrier.getMonth(), calendrier.getYear(), calendrier.getHour(), calendrier.getMin(), ""));
					}
				}
				
		        LineArrayAdapter adapter = new LineArrayAdapter(CalendrierActivity.this, items);
		        setListAdapter(adapter);
				
			} catch(Exception e){ 
				Log.e("Erreur",e.getMessage()); 
			} finally { } 
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calendrier);
		
		TaskObject task = new TaskObject(); 
		task.execute(new String[] {Constantes.FLUX_CALENDRIER_MATCH});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		menu.add(0, 1, 0, "News").setIcon(R.drawable.logo_journal);
		menu.add(0, 2, 0, "Classement").setIcon(R.drawable.logo_classement);
		menu.add(0, 3, 0, "Programme TV").setIcon(R.drawable.logo_tv);
		menu.add(0, 4, 0, "Calendrier").setIcon(R.drawable.logo_calendrier);
		menu.add(0, 5, 0, "Facebook").setIcon(R.drawable.logo_facebook);
		menu.add(0, 6, 0, "Twitter").setIcon(R.drawable.logo_twitter);
	    
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
		case 1:
			intentAccueil = new Intent(this, MainActivity.class);
			startActivity(intentAccueil);
			return true;
			
		case 2:
			intentClassement = new Intent(this, ClassementActivity.class);
			startActivity(intentClassement);
			return true;
			
		case 3:
			intentProgrammeTV = new Intent(this, ProgrammeTvActivity.class);
			startActivity(intentProgrammeTV);
			return true;
			
		case 4:
			intentCalendrier = new Intent(this, CalendrierActivity.class);
			startActivity(intentCalendrier);
			return true;
		
		case 5:
			intentFacebook = new Intent(this, FacebookActivity.class);
			startActivity(intentFacebook);
			return true;
			
		case 6:
			intentTwitter = new Intent(this, TwitterActivity.class);
			startActivity(intentTwitter);
			return true;
			
		default:
			return true;
		}
	}

}
